
using System;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Abp.AutoMapper;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;
using Microsoft.AspNetCore.Mvc;
using Yozeev.BusinessLogic.Dtos;
using Yozeev.BusinessLogic.DomainService;
using Yozeev.BusinessLogic.Authorization;
using Yozeev.BusinessLogic.TicketLogic.Dtos;
using Yozeev.Common;
using Yozeev.UserManagerment.Users;
using Abp.Authorization.Users;

namespace Yozeev.BusinessLogic
{
	/// <summary>
	/// Account应用层服务的接口实现方法  
	///</summary>
	[AbpAuthorize]
	public class TicketAccountAppService : YozeevAppServiceBase, ITicketAccountAppService
    {
        private readonly IRepository<Account, Guid> _entityRepository;

        private readonly IRepository<Activity, Guid> _activityRepository;

        private readonly IRepository<AccountDetail, Guid> _accountDetailRepository;

        private readonly IRepository<TicketDetail, Guid> _ticketDetailRepository;

        private readonly IAccountManager _entityManager;

        private readonly IQueryHelper _queryHelper;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TicketAccountAppService(
        IRepository<Account, Guid> entityRepository
        , IAccountManager entityManager
		, IQueryHelper queryHelper
		, IRepository<Activity, Guid> activityRepository
		, IRepository<AccountDetail, Guid> accountDetailRepository
		, IRepository<TicketDetail, Guid> ticketDetailRepository
		)
        {
             _entityRepository = entityRepository; 
             _entityManager=entityManager;
             _queryHelper = queryHelper;
             _activityRepository = activityRepository;
             _ticketDetailRepository = ticketDetailRepository;
        }


        /// <summary>
        /// 获取TicketAccount的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[HttpPost]
        public async Task<PagedResultDto<AccountListDto>> GetPaged(GetAccountsInput input)
		{

            var expression = _queryHelper.WhereExp<Account>(input.queryData);
			if (AbpUserBase.AdminUserName != GetCurrentUser().UserName)
				expression = _queryHelper.SetWhereExp<Account>(expression, GetViewTypeEnum<Account>(), await GetBranchUser());
			var query = from entity in _entityRepository.GetAll().AsNoTracking()
                        .Where(expression)
                        select new
                        {
                            entity,
                            entity.Collectior,
                            entity.CreatorUser,
							entity.PayMethod,
                        };
            var list = new List<AccountListDto>();
            query.ToList().ForEach(temp => {
                var _entity = temp.entity.MapTo<AccountListDto>();
                _entity.Collectior = temp.Collectior;
				_entity.CreatorUser = temp.CreatorUser;
				_entity.PayMethod = temp.PayMethod;
				list.Add(_entity);
            });
            var count = list.Count();
			list = list.AsQueryable().OrderBy(input.Sorting)
					.PageBy(input)
					.ToList();
			return new PagedResultDto<AccountListDto>(count, list);
		}


		/// <summary>
		/// 通过指定id获取AccountListDto信息
		/// </summary>
		public async Task<AccountListDto> GetById(EntityDto<Guid> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<AccountListDto>();
		}

		/// <summary>
		/// 获取编辑 Account
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task<GetAccountForEditOutput> GetForEdit(NullableIdDto<Guid> input)
		{
			var output = new GetAccountForEditOutput();
            AccountEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<AccountEditDto>();

				//accountEditDto = ObjectMapper.Map<List<accountEditDto>>(entity);
			}
			else
			{
				editDto = new AccountEditDto();
			}

			output.Account = editDto;
			return output;
		}

		/// <summary>
		/// 根据Account ID 获取账单明细
		/// </summary>
		/// <param name="accountId"></param>
		/// <returns></returns>
        public async Task<List<AccountDetailDto>> GetDetail(string accountId)
        {
            var activities = _activityRepository.GetAll()
                .Where(activity => accountId.Contains(activity.Account.Id.ToString()));
            var activityIds = activities.Select(a => a.Id).ToList();
            var tickets = _ticketDetailRepository.GetAll()
                .Where(t => activityIds.Contains(t.ActivityDetail.ActivityId));

			List<AccountDetailDto> result = new List<AccountDetailDto>();
            foreach (var activity in activities)
            {
                List<TicketDetail> t = tickets.Where(m 
                    => m.ActivityDetail.Activity.Id.Equals(activity.Id)).ToList();
                var ticketDtos = t.MapTo<List<TicketDetailListDto>>();
                var accountDetail = activity.MapTo<AccountDetailDto>();
                accountDetail.Tickets = ticketDtos;
				result.Add(accountDetail);
			}

            return result;
        }

		/// <summary>
		/// 添加或者修改Account的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task CreateOrUpdate(CreateOrUpdateAccountInput input)
		{

			if (input.Account.Id.HasValue)
			{
				await Update(input.Account);
			}
			else
			{
				await Create(input.Account);
			}
		}


		/// <summary>
		/// 新增Account
		/// </summary>
		protected virtual async Task<AccountEditDto> Create(AccountEditDto input)
		{
			//TODO:新增前的逻辑判断，是否允许新增

            // var entity = ObjectMapper.Map <Account>(input);
            var entity=input.MapTo<Account>();
			

			entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<AccountEditDto>();
		}

		/// <summary>
		/// 编辑Account
		/// </summary>
		protected virtual async Task Update(AccountEditDto input)
		{
			//TODO:更新前的逻辑判断，是否允许更新

			var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity);

			// ObjectMapper.Map(input, entity);
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除Account信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		public async Task Delete(EntityDto<Guid> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除Account的方法
		/// </summary>
		public async Task BatchDelete(List<Guid> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		/// <summary>
		/// 导出Account为excel表,等待开发。
		/// </summary>
		/// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


